package server.command.client;

import app_kvServer.KVServer;
import common.messages.KVMessage.StatusType;
import utils.*;

public class CommandDelete implements ICommand {
	private IKeyValueStorage storage;
	private String key;
	private KVServer server;
	
	public CommandDelete(KVServer server, IKeyValueStorage storage, String key) {
		this.key = key;
		this.storage = storage;
		this.server = server;
	}
	
	@Override
	public String execute() {
		String keyHash = CommonUtil.hashString(key);
		if (KVServer.isInRange(keyHash, server.getRangeStart(), server.getRangeEnd())) {
			if (storage.isWriteLockEnabled()) {
				return ClientInputHandler.composeClientResponse(StatusType.SERVER_WRITE_LOCK, "Write lock enabled Enabled", "");
			}
			String value = (String) storage.remove(keyHash);
			return ClientInputHandler.composeClientResponse(StatusType.DELETE_SUCCESS, key, value);
		} 
		else {
			/** TODO what if the metadata is out of date? **/
			return ClientInputHandler.composeClientResponse(StatusType.SERVER_NOT_RESPONSIBLE, key, "");
		}
	}
}
